import Hero from "./hero";
import {KILL_SCORE, WEAPON_SCORE_MAPPING} from "./config/config";
import HeroSpine from "./hero/heroSpine";
import {globalConfig} from "./config/globalConfig";
import {GameVar, GlobalObject} from "./game/GameVar";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Weapon extends cc.Component {

  private _hero: cc.Node = null;
  myHero: Hero = null;
  myHeroSpine: HeroSpine = null;
  private _level: number = 1;

  onLoad() {
    this.myHero = this.node.parent.getComponent(Hero)
    this.myHeroSpine = this.node.parent.getComponent(HeroSpine)
    this.setLevel(this._level)
  }

  set hero(value: cc.Node) {
    this._hero = value;
  }

  onCollisionEnter(other: cc.BoxCollider, self: cc.BoxCollider) {
    if (self.node === other.node.getChildByName('weapon')) {
      return;
    }
    const otherHero = other.getComponent(Hero)
    if (!this.myHero.immortal && !otherHero.immortal) {
      otherHero.beHit(this.myHero.user.username);
      this.myHero.addScore(KILL_SCORE);
      this.myHero.addKill();
      if (this.myHero.user.uid === GameVar.userInfo.uid) {
        GlobalObject.voiceSource.playHit();
      } else if (otherHero.user.uid === GameVar.userInfo.uid) {
        GlobalObject.voiceSource.playDied();
        GlobalObject.voiceSource.stopAcc();
      }
    }
  }

  checkScore(score: number) {
    const config: any = globalConfig.model_config[this._level - 1]
    if (!config) {
      return;
    }
    if (score > config.exp) {
      this.setLevel(this._level + 1)
    }
  }

  public setLevel(level: number) {
    const config: any = globalConfig.model_config[level - 1]
    if (!config) {
      return;
    }
    this.node.width = config.width;
    this.node.height = config.length;
    const collider: cc.BoxCollider = this.node.getComponent(cc.BoxCollider)
    collider.size.width = config.width;
    collider.size.height = config.length;
    collider.offset.y = config.length / 2;
    this._level = level;
    this.myHeroSpine.upgradeToLevel(level)
  }
}
